package com.yanqu.road.dao.db;

import com.yanqu.road.utils.LogUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.pool.HikariPool;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

public class MysqlPool implements DbPool {

    private HikariPool pool;

    public MysqlPool(DbPoolConfig poolConfig) {
        HikariConfig config = new HikariConfig();
        config.setUsername(poolConfig.getUserName());
        config.setPassword(poolConfig.getPassword());
        config.setJdbcUrl(poolConfig.getUrl());
        config.setMaximumPoolSize(poolConfig.getMaxConnSize());
        config.setPoolName(poolConfig.getPoolName());
        pool = new HikariPool(config);
    }


    @Override
    public Connection getConnection() {
        try {
            return pool.getConnection();
        } catch (SQLException e) {
            LogUtils.ERROR.error("getConnection", e);
        }
        return null;
    }

    @Override
    public String getColDetail(int types, int len) {
        switch (types) {
            case Types.INTEGER:
                return "int(11)";
            case Types.TINYINT:
                return "tinyint(3)";
            case Types.SMALLINT:
                return "smallint(5)";
            case Types.BIGINT:
                return "BIGINT(20)";
            case Types.VARCHAR:
                return "varchar(" + len + ")";
            case Types.LONGVARCHAR:
                return "text ";
            case Types.TIMESTAMP:
                return "datetime";
            case Types.BIT:
                return "tinyint(1)";
        }
        return "text";
    }

    @Override
    public String getColDefault(int types) {
        switch (types) {
            case Types.INTEGER:
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.BIGINT:
            case Types.BIT:
                return " DEFAULT 0";
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                return " ";
            case Types.TIMESTAMP:
                return " DEFAULT '1970-01-01 08:00:00'";
        }
        throw new RuntimeException("找不到对应的默认值");
    }
}
